<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

// 上传逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['dbfile'])) {
    $tmp_name = $_FILES['dbfile']['tmp_name'];
    $ext = pathinfo($_FILES['dbfile']['name'], PATHINFO_EXTENSION);
    $uploads_dir = __DIR__ . '/uploads';
    if (!is_dir($uploads_dir)) {
        mkdir($uploads_dir, 0777, true);
    }
    $db_file = $uploads_dir . '/sqlite_' . uniqid() . '.' . $ext;
    if (move_uploaded_file($tmp_name, $db_file)) {
        $_SESSION['db_file'] = $db_file;
        header("Location: ?show=1");
        exit;
    } else {
        echo "<p style='color:red'>文件上传失败，请检查uploads文件夹权限！</p>";
        var_dump($_FILES['dbfile']);
        exit;
    }
}

// 删除文件请求
if (isset($_GET['delete']) && isset($_SESSION['db_file'])) {
    if (file_exists($_SESSION['db_file'])) unlink($_SESSION['db_file']);
    unset($_SESSION['db_file']);
    exit('ok');
}

// 展示数据库内容
if (isset($_GET['show']) && isset($_SESSION['db_file'])) {
    $db_file = $_SESSION['db_file'];
    if (!file_exists($db_file)) {
        echo "<p style='color:red'>数据库文件不存在！</p>";
        exit;
    }
    $db = new SQLite3($db_file);
    $tables = [];
    $res = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");
    while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
        $tables[] = $row['name'];
    }
    if (empty($tables)) {
        echo "<p style='color:red'>数据库中没有表，或不是有效的SQLite数据库！</p>";
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>SQLite数据库查看器</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            body {
                font-family: 'Segoe UI', Arial, sans-serif;
                margin: 0;
                background: linear-gradient(120deg, #e3f0fc 0%, #f4f6fa 100%);
                min-height: 100vh;
            }
            .main-card {
                max-width: 1200px;
                margin: 36px auto 0 auto;
                background: #fff;
                border-radius: 16px;
                box-shadow: 0 8px 32px 0 rgba(60,72,88,.12);
                padding: 32px 24px 24px 24px;
            }
            .tabs {
                display: flex;
                border-bottom: 2px solid #e0e0e0;
                margin-bottom: 0;
                background: #fff;
                border-radius: 12px 12px 0 0;
                box-shadow: 0 2px 8px 0 rgba(60,72,88,.04);
                overflow-x: auto;
                gap: 2px;
            }
            .tab {
                padding: 14px 32px 12px 32px;
                cursor: pointer;
                border: none;
                border-bottom: 2px solid transparent;
                background: none;
                font-size: 1.08rem;
                color: #555;
                transition: color 0.2s, border 0.2s, background 0.2s;
                outline: none;
                position: relative;
            }
            .tab:not(:last-child)::after {
                content: '';
                position: absolute;
                right: 0; top: 30%; bottom: 30%;
                width: 1px;
                background: #e0e0e0;
            }
            .tab.active {
                color: #1976d2;
                border-bottom: 3px solid #1976d2;
                font-weight: bold;
                background: linear-gradient(90deg, #e3f0fc 0%, #fff 100%);
                z-index: 1;
            }
            .table-content {
                display: none;
                background: #fff;
                border-radius: 0 0 12px 12px;
                box-shadow: 0 2px 8px 0 rgba(60,72,88,.04);
                padding: 24px 8px 32px 8px;
                margin-bottom: 32px;
                overflow-x: auto;
                max-height: 60vh;
            }
            .table-content.active {
                display: block;
                animation: fadeIn 0.4s;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(20px); }
                to { opacity: 1; transform: none; }
            }
            table {
                border-collapse: separate;
                border-spacing: 0;
                width: 100%;
                min-width: 600px;
                background: #fff;
                border-radius: 8px;
                overflow: hidden;
                box-shadow: 0 2px 8px 0 rgba(60,72,88,.04);
            }
            th, td {
                border-bottom: 1px solid #e0e0e0;
                padding: 8px 14px;
                text-align: left;
                font-size: 0.98rem;
                max-width: 320px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
            th {
                background: #f7fafd;
                font-weight: 600;
                position: sticky;
                top: 0;
                z-index: 2;
            }
            tr:last-child td {
                border-bottom: none;
            }
            tr:hover {
                background: #e3f0fc;
                transition: background 0.2s;
            }
            .no-data {
                text-align: center;
                color: #aaa;
                font-size: 1.1rem;
                padding: 32px 0;
            }
            @media (max-width: 900px) {
                .main-card { padding: 10px 2vw 10px 2vw; }
                table, th, td { font-size: 0.92rem; }
            }
            @media (max-width: 600px) {
                .main-card { width: 99vw; margin: 12px auto; padding: 8px 2vw; }
                .tabs { flex-wrap: wrap; }
                .tab { padding: 10px 10px; font-size: 0.98rem; }
                .table-content { padding: 8px 2px 16px 2px; }
                table, th, td { font-size: 0.92rem; }
            }
        </style>
    </head>
    <body>
    <div class="main-card">
        <h2>SQLite数据库查看器</h2>
        <div class="tabs">
            <?php foreach ($tables as $i => $table): ?>
                <div class="tab<?= $i==0?' active':'' ?>" data-tab="<?= $i ?>"><?= htmlspecialchars($table) ?></div>
            <?php endforeach; ?>
        </div>
        <?php foreach ($tables as $i => $table): ?>
            <div class="table-content<?= $i==0?' active':'' ?>" id="tab-<?= $i ?>">
                <h3 style="margin:18px 0 10px 0; font-size:1.18rem; color:#1976d2; letter-spacing:1px; font-weight:600;">
                    <?= htmlspecialchars($table) ?>
                </h3>
                <div style="overflow-x:auto;">
                <table>
                    <tr>
                        <?php
                        $res = $db->query("PRAGMA table_info('$table')");
                        $cols = [];
                        while ($col = $res->fetchArray(SQLITE3_ASSOC)) {
                            $cols[] = $col['name'];
                            echo '<th>' . htmlspecialchars($col['name']) . '</th>';
                        }
                        ?>
                    </tr>
                    <?php
                    $res = $db->query("SELECT * FROM '$table' LIMIT 1000");
                    $rowCount = 0;
                    while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
                        $rowCount++;
                        echo '<tr>';
                        foreach ($cols as $col) {
                            echo '<td title="' . htmlspecialchars($row[$col]) . '">' . htmlspecialchars($row[$col]) . '</td>';
                        }
                        echo '</tr>';
                    }
                    if ($rowCount === 0) {
                        echo '<tr><td class="no-data" colspan="' . count($cols) . '">暂无数据</td></tr>';
                    }
                    ?>
                </table>
                </div>
            </div>
        <?php endforeach; ?>
        <script>
            // 标签切换
            document.querySelectorAll('.tab').forEach(function(tab, idx){
                tab.onclick = function(){
                    document.querySelectorAll('.tab').forEach(t=>t.classList.remove('active'));
                    document.querySelectorAll('.table-content').forEach(c=>c.classList.remove('active'));
                    tab.classList.add('active');
                    document.getElementById('tab-'+idx).classList.add('active');
                }
            });
            // 页面关闭/刷新时删除数据库
            window.addEventListener('beforeunload', function(){
                navigator.sendBeacon('?delete=1');
            });
        </script>
    </div>
    <footer style="position:fixed;left:0;right:0;bottom:0;text-align:center;color:#888;font-size:0.98rem;padding:12px 0 10px 0;letter-spacing:1px;background:rgba(255,255,255,0.95);box-shadow:0 -2px 8px 0 rgba(60,72,88,.04);z-index:99;">
        © 2020-2025 凌霄玉阙台 & 谭宝龙
    </footer>
    </body>
    </html>
    <?php
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>SQLite数据库查看器</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { font-family: 'Segoe UI', Arial, sans-serif; margin: 0; background: #f4f6fa; }
        .upload-box {
            border: 1px solid #e0e0e0;
            box-shadow: 0 4px 24px 0 rgba(60,72,88,.08);
            border-radius: 12px;
            padding: 36px 32px 32px 32px;
            width: 350px;
            margin: 100px auto;
            background: #fff;
            text-align: center;
        }
        .upload-box h2 {
            margin-bottom: 24px;
            font-size: 1.4rem;
            font-weight: 700;
        }
        .upload-box input[type="file"] {
            margin: 12px 0 20px 0;
        }
        .upload-box button {
            background: #1976d2;
            color: #fff;
            border: none;
            border-radius: 6px;
            padding: 10px 28px;
            font-size: 1rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        .upload-box button:hover {
            background: #125ea7;
        }
        .tabs {
            display: flex;
            border-bottom: 2px solid #e0e0e0;
            margin-bottom: 0;
            background: #fff;
            border-radius: 12px 12px 0 0;
            box-shadow: 0 2px 8px 0 rgba(60,72,88,.04);
            overflow-x: auto;
        }
        .tab {
            padding: 12px 28px;
            cursor: pointer;
            border: none;
            border-bottom: 2px solid transparent;
            background: none;
            font-size: 1.08rem;
            color: #555;
            transition: color 0.2s, border 0.2s;
            outline: none;
        }
        .tab.active {
            color: #1976d2;
            border-bottom: 2.5px solid #1976d2;
            font-weight: bold;
            background: #f4f6fa;
        }
        .table-content {
            display: none;
            background: #fff;
            border-radius: 0 0 12px 12px;
            box-shadow: 0 2px 8px 0 rgba(60,72,88,.04);
            padding: 24px 12px 32px 12px;
            margin-bottom: 32px;
        }
        .table-content.active {
            display: block;
        }
        table {
            border-collapse: separate;
            border-spacing: 0;
            width: 100%;
            margin-top: 10px;
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px 0 rgba(60,72,88,.04);
        }
        th, td {
            border-bottom: 1px solid #e0e0e0;
            padding: 8px 14px;
            text-align: left;
            font-size: 0.98rem;
        }
        th {
            background: #f7fafd;
            font-weight: 600;
        }
        tr:last-child td {
            border-bottom: none;
        }
        tr:hover {
            background: #e3f0fc;
            transition: background 0.2s;
        }
        @media (max-width: 600px) {
            .upload-box { width: 98vw; margin: 24px auto; padding: 18px 4vw; }
            .tabs { flex-wrap: wrap; }
            .tab { padding: 10px 10px; font-size: 0.98rem; }
            .table-content { padding: 8px 2px 16px 2px; }
            table, th, td { font-size: 0.92rem; }
        }
    </style>
</head>
<body>
    <div class="upload-box" id="drop-area">
        <h2>上传SQLite数据库文件</h2>
        <form id="uploadForm" method="post" enctype="multipart/form-data">
            <input type="file" name="dbfile" id="fileElem" accept=".db,.sqlite,.sqlite3" style="display:none" required>
            <label for="fileElem" id="fileLabel" style="display:block;cursor:pointer;padding:32px 0;border:2px dashed #1976d2;border-radius:10px;background:#f7fafd;color:#1976d2;font-size:1.08rem;transition:background 0.2s;">
                拖拽文件到此处，或点击选择文件
            </label>
            <div id="fileName" style="margin:10px 0 18px 0;color:#1976d2;font-weight:500;"></div>
            <button type="submit">上传并查看</button>
        </form>
    </div>
    <script>
    const dropArea = document.getElementById('drop-area');
    const fileElem = document.getElementById('fileElem');
    const fileLabel = document.getElementById('fileLabel');
    const fileName = document.getElementById('fileName');
    dropArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        fileLabel.style.background = '#e3f0fc';
    });
    dropArea.addEventListener('dragleave', function(e) {
        fileLabel.style.background = '#f7fafd';
    });
    dropArea.addEventListener('drop', function(e) {
        e.preventDefault();
        fileLabel.style.background = '#f7fafd';
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            fileElem.files = e.dataTransfer.files;
            fileName.textContent = e.dataTransfer.files[0].name;
        }
    });
    fileElem.addEventListener('change', function(e) {
        if (fileElem.files.length > 0) {
            fileName.textContent = fileElem.files[0].name;
        } else {
            fileName.textContent = '';
        }
    });
    </script>
    <footer style="position:fixed;left:0;right:0;bottom:0;text-align:center;color:#888;font-size:0.98rem;padding:12px 0 10px 0;letter-spacing:1px;background:rgba(255,255,255,0.95);box-shadow:0 -2px 8px 0 rgba(60,72,88,.04);z-index:99;">
        © 2020-2025 凌霄玉阙台 & 谭宝龙
    </footer>
</body>
</html>